package org.tong.pdf;

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.parser.data.PathRenderInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templateresolver.StringTemplateResolver;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author
 * @date 2022-10-09 13:51
 */
@Controller
public class PrintPdfController {

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private ConverterProperties converterProperties;

    @GetMapping("/html2pdf")
    public void orderPdf(Model model, HttpServletResponse response) throws IOException {
        Context context = new Context();
        context.setVariable("data", initMap());
        processPdfLocal(context, "order-template.html", "order.pdf", response);
    }

    @GetMapping("/html")
    public String orderHtml(Model model, HttpServletResponse response) throws IOException {
        Context context = new Context();
        model.addAttribute("data", initMap());
        return "order-template.html";
    }


    private void processPdf(Context context, String template, String fileName, HttpServletResponse response) throws IOException {
        String html = templateEngine.process(template, context);
        String filenameEncoding = URLEncoder.encode(fileName, "utf-8");
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "filename=" + fileName);
        // 写出
        PdfDocument doc = new PdfDocument(new PdfWriter(response.getOutputStream()));
        doc.setDefaultPageSize(PageSize.A4);
        HtmlConverter.convertToPdf(html, doc, converterProperties);
    }

    private void processPdfLocal(Context context, String template, String fileName, HttpServletResponse response) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(PrintPdfController.class.getClassLoader().getResourceAsStream("templates/" + template)));
        String html = reader.lines().collect(Collectors.joining());
        TemplateEngine engine = new TemplateEngine();
        //engine.setTemplateResolver(new StringTemplateResolver());
        long start = System.currentTimeMillis();
        String val = engine.process(html, context);

        String filenameEncoding = URLEncoder.encode(fileName, "utf-8");
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "filename=" + fileName);
        // 写出
        PdfDocument doc = new PdfDocument(new PdfWriter(response.getOutputStream()));
        doc.setDefaultPageSize(PageSize.A4);
        HtmlConverter.convertToPdf(val, doc, converterProperties);
        // 10万数据耗时50秒左右
        System.out.println("耗时:" + (System.currentTimeMillis() - start));
    }


    private Map<String, Object> initMap() {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("inquireCode", "1234");
        dataMap.put("inquireName", "询价单名称");
        dataMap.put("relationName", "关联数据名称");
        dataMap.put("relationCode", "关联数据编号");
        dataMap.put("supplierName", "共产国际");
        dataMap.put("dealRemark", "处理标注");
        dataMap.put("purchaseName", "李强");
        dataMap.put("createTime", new Date().toString());
        // 表
        dataMap.put("header", Arrays.asList("名称"));
        List<String> rows = new ArrayList<>();
        for (int i = 0; i < 100000; i++) {
            rows.add("数据" + i);
        }
        dataMap.put("rows", rows);
        return dataMap;
    }
}
